<template>
    <div class="mydiv" ref="mydiv" :style="{height:MydivHeight}">
        <div class="bg"></div>
        <comeback :getURL ="goType"></comeback>
        <div class="goods-banner">
            <div class="banner-img">
                <!-- <img src="../../assets/11/banner.png" v-if="$route.path.indexOf('recommend') != -1"> -->
                <!-- <img :src="imgSrc" v-if="$route.path.indexOf('recommend') == -1"> -->
                <img :src="imgSrc">
            </div>
        </div>
        <section class="seach">
            <input type="text" placeholder="请输入商品名称" v-model="seachCnt">
            <section>
                <img src="../../assets/other/seach.png" @click="seach" alt="">
            </section>
        </section>
        <section class="goodsList">
            <!-- 排序 -->
            <section class="seachTit">
                <section @click="sortFnc('sell')">
                    <span>销量</span>
                    <img src="../../assets/other/ASC.png" alt="" v-if="saleSort == 'ASC'">
                    <img src="../../assets/other/DESC.png" alt="" v-if="saleSort == 'DESC'">
                </section>
                <section @click="sortFnc('defaultPrice')">
                    <span>价格</span>
                    <img src="../../assets/other/ASC.png" alt="" v-if="priceSort == 'ASC'">
                    <img src="../../assets/other/DESC.png" alt="" v-if="priceSort == 'DESC'">
                </section>
            </section>
            <section :class="{'new-arrival-goodses':isRecommend}" v-infinite-scroll="loadMore"
            infinite-scroll-disabled="loading"
            infinite-scroll-distance="10"
            infinite-scroll-immediate-check="loading">
                <div v-for="(goods,index) of goodsList" :key="index" @click="turnDetailPage(goods.id)" class="goods" :class="{'new-arrival-goods':isRecommend}">
                    <div v-if="isFlashSale">
                        <div class="goods-second-kill" v-if="isCountDown[index]">
                            <span>离活动结束还有：</span>
                            <count-down :startTime="currentTime" :endTime="goods.endTime" :dayTxt="'天'" :hourTxt="'小时'" :minutesTxt="'分钟'" :secondsTxt="'秒'"></count-down>
                        </div>
                        <div class="goods-second-kill" v-if="!isCountDown[index]">
                            <div>
                                <div class="sale-preview">抢购预告</div>
                                <span>预计</span>
                                <span>{{goods.startTime | formatDate}}</span>
                                <span>开始</span>
                            </div>
                        </div>
                    </div>
                    <section class="goods-img" :class="{'new-arrival-goods-img':isRecommend}">
                        <img :src="goods.thumbnail" alt="">
                    </section>
                    <section class="goods-info" :class="{'new-arrival-goods-info':isRecommend}">
                        <p :class="{'new-arrival-goods-name':isRecommend}">
                            {{goods.name}}
                        </p>
                        <p class="goods-price" :class="{'new-arrival-goods-price':isRecommend}">
                            ￥{{goods.price}}
                        </p>
                        <section>
                            <section class="goods-income" :class="{'new-arrival-goods-income':isRecommend}" @click="lookEarnings(goods.clearPrice, goods.defaultPrice)" @click.stop v-if="userInfo.channelLv!=-1&&!isFundsell">
                                收益
                            </section>
                            <section v-if="userInfo.channelLv==-1" class="goods-income-hidden"></section>
                        </section>
                    </section>
                    <section class="shop-cart" :class="{'new-arrival-goods-shop-cart':isRecommend}">
                        <img src="../../assets/mall/mallCart.png" alt="">
                    </section>
                </div>
                <loadmore v-show="loadingDom"></loadmore>
                <!-- 收益 -->
                <earningsPop ref="earnings"></earningsPop>
            </section>
        </section>
    </div>
</template>
<script>
    import { InfiniteScroll } from 'mint-ui'
    import CountDown from 'vue2-countdown'
    import loadmore from '../../components/loadmore'
    import { product } from '../../libs/interface'
    import comeback from '../../components/comeback.vue'
    import earningsPop from '../../components/earningsPop'
    import { userInfoGet, WXShare } from '../../libs/publicMethod'
    export default {
        components: { comeback, loadmore, InfiniteScroll, product, userInfoGet, earningsPop, CountDown, WXShare },
        data () {
            return {
                goType: '/mall',
                userInfo: userInfoGet(),
                MydivHeight: '',
                isRecommend: false,
                isFlashSale: false,
                imgSrc: '',
                goodsList: [],
                seachCnt: '', // 搜索框内容
                loading: false, // 下拉参数
                loadingDom: false,
                categoryList: sessionStorage.getItem('categoryList') ? JSON.parse(sessionStorage.getItem('categoryList')) : [], // 商品分类列表
                offset: sessionStorage.getItem('saleScrollOffset') ? JSON.parse(sessionStorage.getItem('saleScrollOffset')).offset || 0 : 0,
                sortField: sessionStorage.getItem('sortField') ? sessionStorage.getItem('sortField') : 'sell', //排序字段
                saleSort: sessionStorage.getItem('saleSort') ? sessionStorage.getItem('saleSort') : 'DESC', // 销量排序
                priceSort: sessionStorage.getItem('priceSort') ? sessionStorage.getItem('priceSort') : 'DESC', // 价钱排序
                currentTime: 0,
                // date1: 0,
                // date2: 0,
                // date3: 0,
                isCountDown: [],
                isFundsell: false
                // endCountDown: 
            }
        },
        mounted () {
            let vm = this
            // vm.date1 = '2018-09-11 00:00:00';
            // vm.date2 = '2018-09-12 00:00:00';
            // vm.date3 = '2018-09-13 00:00:00';
            // vm.date1 = new Date(vm.date1.replace(/-/g, '/')).getTime()
            // vm.date2 = new Date(vm.date2.replace(/-/g, '/')).getTime()
            // vm.date3 = new Date(vm.date3.replace(/-/g, '/')).getTime()
            // console.log(new Date())
            document.body.style.paddingBottom = 0
            vm.MydivHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight + 'px'
            let params = {
                productType: vm.$route.params.column,
                runType: 2,
                limit: 10,
                offset: 0,
                likeStr: '',
                sidx: 'createTime',
                sord: 'DESC'
            }
            if (location.href.indexOf('hotCake') != -1) {
                params.runType = 2
            }
            if (location.href.indexOf('recommend') != -1) {
                params.runType = 1
                vm.isRecommend = true
            }
            if (location.href.indexOf('flashSale') != -1) {
                params.runType = 3
                vm.isFlashSale = true
            }
            if (location.href.indexOf('sellAgain') != -1) {
                params.runType = -1
                params.productType = -3
                vm.isRecommend = true
                vm.isFundsell = true
            }
            if (sessionStorage.getItem('saleScrollOffset')) {
                let saleSO = JSON.parse(sessionStorage.getItem('saleScrollOffset'))
                saleSO.offset += 10
                params.limit = saleSO.offset
                product(params, (data) => {
                    if (data.code == 1 && data.payload.length > 0) {
                        vm.goodsList = data.payload
                        vm.imgSrc = vm.goodsList[Math.round(Math.random() * (vm.goodsList.length - 1))].banner.split(',')[0]
                        vm.currentTime = new Date().getTime()
                        for (let elem of vm.goodsList) {
                            elem.price = (elem.defaultPrice / 100).toFixed(2)
                            vm.isCountDown.push(vm.currentTime > elem.startTime && vm.currentTime < elem.endTime ? true : false)
                        }
                        vm.$nextTick(() => {
                            // document.documentElement.scrollTop = saleSO.scroll
                            vm.$refs.mydiv.scrollTop = saleSO.scroll
                            setTimeout(() => {
                                sessionStorage.removeItem('saleScrollOffset')
                            }, 0)
                        })
                    }
                    if (data.code === 0) {
                        vm.goodsList = []
                        vm.$toast('暂未请求到数据,请稍后再试')
                    }
                    if (data.payload.length === 0) {
                        vm.goodsList = []
                        vm.$toast('暂无商品')
                    }
                })
            } else {
                product(params, (data) => {
                    if (data.code === 1 && data.payload.length > 0) {
                        vm.goodsList = data.payload
                        vm.imgSrc = vm.goodsList[Math.round(Math.random() * (vm.goodsList.length - 1))].banner.split(',')[0]
                        vm.currentTime = new Date().getTime()
                        for (let elem of vm.goodsList) {
                            elem.price = (elem.defaultPrice / 100).toFixed(2)
                            vm.isCountDown.push(vm.currentTime > elem.startTime && vm.currentTime < elem.endTime ? true : false)
                        }
                    } else {
                        vm.goodsList = []
                        if (data.code === 0) {
                            vm.$toast('暂未请求到数据,请稍后再试')
                        } else {
                            vm.$toast('暂无商品')
                        }
                    }
                    // if (data.code === 0) {
                    //     vm.goodsList = []
                    //     vm.$toast('暂未请求到数据,请稍后再试')
                    // }
                    // if (data.code === 1 && data.payload.length === 0) {
                    //     vm.goodsList = []
                    //     vm.$toast('暂无商品')
                    // }
                })
            }
            // 分享
            var Sdata = {                                                          //分享请求配置
                gotoPage:this.$route.path,                                          //邀请者链接         
                inviterID: userInfoGet().id,                                                        //链接带的参数
                type: 1,
                desc: '享高端品质，品精致生活，尽在乐销商城！',
                imgUrl:'http://120.77.73.224:80/group1/M00/00/05/eE1J4FoedWqALp8pAABLzkI6gxQ837.png',                                                       //链接图片（小图）     
                shareTitle: '【' + userInfoGet().nick + '】' + '邀请您一起逛乐销商城'               //邀请话
            }
            WXShare.hideOptionMenu()
        },
        methods: {
            turnDetailPage (id) {
                let vm = this
                if (location.href.indexOf('sellAgain') != -1) {
                    // sessionStorage.setItem('coupon', JSON.stringify({ coupon: false, isFund: true }))
                    sessionStorage.setItem('isFund', JSON.stringify({ isFund: true }))
                    sessionStorage.removeItem('coupon')
                } else {
                    // sessionStorage.setItem('coupon', JSON.stringify({ coupon: false, isFund: false }))
                    sessionStorage.removeItem('isFund')
                    sessionStorage.removeItem('coupon')
                }
                // sessionStorage.setItem('saleScrollOffset', JSON.stringify({ scroll: document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop, offset: vm.offset }))
                sessionStorage.setItem('saleScrollOffset', JSON.stringify({ scroll: vm.$refs.mydiv.scrollTop, offset: vm.offset }))
                vm.$router.push('/goods/'+id)
            },
            // 搜索
            seach () {
                let vm = this
                let params = {
                    productType: vm.$route.params.column,
                    runType: 2,
                    limit: 10,
                    offset: 0,
                    likeStr: vm.seachCnt,
                    sidx: vm.sortField,
                    sord: vm.saleSort ? vm.saleSort : vm.priceSort
                }
                if (location.href.indexOf('hotCake') != -1) {
                    params.runType = 2
                }
                if (location.href.indexOf('recommend') != -1) {
                    params.runType = 1
                }
                if (location.href.indexOf('flashSale') != -1) {
                    params.runType = 3
                }
                if (location.href.indexOf('sellAgain') != -1) {
                    params.runType = -1
                    params.productType = -3
                }
                product(params, (data) => {
                    if (data.code == 1) {
                        console.log(data)
                        vm.goodsList = data.payload
                        for (let p of vm.goodsList) {
                            p.price = (p.defaultPrice / 100).toFixed(2)
                        }
                    } else {
                        vm.goodsList = [];
                        vm.$toast('暂未请求到数据,请稍后再试')
                    }
                })
            },
            // 排序
            sortFnc (val) {
                let vm = this
                sessionStorage.setItem('sortField', val)
                vm.offset = 0
                vm.loading = false
                switch (val) {
                    case 'sell':
                        if (vm.saleSort == 'ASC') {
                            vm.saleSort = 'DESC'
                            vm.sortFncS('sell', 'DESC')
                            sessionStorage.setItem('saleSort', 'DESC')
                        } else {
                            vm.saleSort = 'ASC'
                            vm.sortFncS('sell', 'ASC')
                            sessionStorage.setItem('saleSort', 'ASC')
                        }
                        break;
                    case 'defaultPrice':
                        if (vm.priceSort == 'ASC') {
                            vm.priceSort = 'DESC'
                            vm.sortFncS('defaultPrice', 'DESC')
                            sessionStorage.setItem('priceSort', 'DESC')
                        } else {
                            vm.priceSort = 'ASC'
                            vm.sortFncS('defaultPrice', 'ASC')
                            sessionStorage.setItem('priceSort', 'ASC')
                        }
                        break;
                }
            },
            sortFncS (sidx, sord) {
                let vm = this
                let params = {
                    productType: vm.$route.params.column,
                    runType: 2,
                    limit: 10,
                    offset: 0,
                    likeStr: vm.seachCnt,
                    sidx: sidx,
                    sord: sord
                }
                if (location.href.indexOf('hotCake') != -1) {
                    params.runType = 2
                }
                if (location.href.indexOf('recommend') != -1) {
                    params.runType = 1
                }
                if (location.href.indexOf('flashSale') != -1) {
                    params.runType = 3
                }
                if (location.href.indexOf('sellAgain') != -1) {
                    params.runType = -1
                    params.productType = -3
                }
                product(params, (data) => {
                    if (data.code == 1 && data.payload.length > 0) {
                        this.goodsList = data.payload
                        for (let p of this.goodsList) {
                            p.price = (p.defaultPrice / 100).toFixed(2)
                        }
                        params.limit = data.payload.length
                    } else {
                        vm.goodsList = [];
                        vm.$toast('暂未请求到数据,请稍后再试')
                    }
                })
            },
            // 上拉加载更多
            loadMore () {
                let vm = this
                if(sessionStorage.getItem('saleScrollOffset')) return null
                vm.loading = true
                vm.loadingDom = true
                vm.offset += 10
                let params = {
                    productType: vm.$route.params.column,
                    runType: 2,
                    limit: 10,
                    offset: vm.offset,
                    likeStr: vm.seachCnt,
                    sidx: 'createTime',
                    sord: 'DESC'
                }
                if (location.href.indexOf('hotCake') != -1) {
                    params.runType = 2
                }
                if (location.href.indexOf('recommend') != -1) {
                    params.runType = 1
                }
                if (location.href.indexOf('flashSale') != -1) {
                    params.runType = 3
                }
                if (location.href.indexOf('sellAgain') != -1) {
                    params.runType = -1
                    params.productType = -3
                }
                product(params, (data) => {
                    if (data.code == 1 && data.payload.length > 0) {
                        vm.$nextTick(() => {
                            data.payload.forEach((item) => {
                                vm.goodsList.push(item)
                            })
                            for (let p of this.goodsList) {
                                p.price = (p.defaultPrice / 100).toFixed(2)
                            }
                        })
                        vm.loading = false
                    } else {
                        vm.loading = true
                        vm.offset -= 10
                        vm.$toast('暂未请求到数据,请稍后再试')
                    }
                    vm.loadingDom = false
                })
            },
            // 查看收益
            lookEarnings(clearPrice, defaultPrice) {
                let vm = this
                vm.$refs.earnings.showbox(true);
                vm.$refs.earnings.computeEarnings(clearPrice, defaultPrice);
            },
        },
        filters: {
            formatDate (input) {
                var d = new Date(input)
                var year = d.getFullYear()
                var month = d.getMonth() + 1
                var day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate()
                var hour = d.getHours()
                var minutes = d.getMinutes()
                var seconds = d.getSeconds()
                return month + '月' + day + '日' + hour + ':' + minutes + ':' + seconds
            }
        }
    }
</script>
<style scoped>
a{
  text-decoration: none;
  outline: none;
  color: #000;
  -webkit-tap-highlight-color:rgba(255,0,0,0)
}
.mydiv{
    overflow: auto;
}
.bg{
    width: 100%;
    height: 3.5rem;
    position: absolute;
    border-radius: .2rem;
    z-index: 5;
    background: linear-gradient(180deg,rgba(0,0,0,.7),rgba(0,0,0,0))
}
.goods-banner{
    background-color: #fff;
}
.banner-img{
    width: 100%;
    height: 16rem;
    position: relative;
}
.banner-img img{
    width: 100%;
    height: 100%;
}
/* 搜索框 */
.seach{
    position: absolute;
    width: 90%;
    top: 0;
    text-align: center;
    margin-left: 10%;
    margin-top: 2%;
    z-index: 6;
}
.seach input{
    padding: .5rem;
    border-radius: 1rem;
    border: 1px solid rgba(240, 240, 240, 1);
    outline: none;
    width: 80%;
    background-color: transparent;
}
.seach input::placeholder{
    color: rgba(240, 240, 240, 1);
}
.seach section{
    width: 1.1rem;
    position: absolute;
    top: 20%;
    right: 10%;
}
.seach section img{
    width: 100%;
}
.goodsList{
    background-color: #fff;
}
/* 排序 */
.seachTit{  
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    text-align: center;
    font-size: .8rem;
    padding-bottom: .3rem;
    padding: .5rem 0;
    background-color: #fff;
}
.seachTit span{
    white-space: nowrap;
}
.seachTit section{
    display: flex;
    flex-direction: row;
    align-items: center;
    text-align: center;
}
.seachTit img{
    height: 1.2rem;
    margin-left: .5rem;
}
.goods{
    display: flex;
    border-radius: .5rem;
    overflow: hidden;
    box-shadow:1px 1px 8px rgba(185,182,168,0.5);
    width: 94%;
    height: 8rem;
    margin: 0 auto 1rem;
    background-color: #fff;
    position: relative;
}
.goods-img{
    width: 50%;
    height: 8rem;
    padding: 0;
    margin: 0;
}
.goods-img img{
    display: block;
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}
.goods-second-kill{
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 20%;
    font-size: .7rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(242,49,98,.8);
    color: rgba(240, 240, 240, 1);
    z-index: 10;
}
.sale-preview{
    width: 4rem;
    display: inline-block;
    border-radius: 1.9rem;
    transform: scale(.7,.7);
    text-align: center;
    height: 1rem;
    line-height: 1rem;
    border: 1px solid #fff;
    font-weight: lighter;
}
.goods-info{
    width: 50%;
    margin-left: 2rem;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    text-align: left;
    font-size: .8rem;
}
.goods-price{
    color: rgb(226,35,25);
}
.goods-income{
    width: 2.5rem;
    height: 1.5rem;
    line-height: 1.5rem;
    text-align: center;
    border-radius: 1rem;
    border: 1px solid #333;
}
.goods-income-hidden{
    width: 2.5rem;
    height: 1.5rem;
    border: 1px solid #fff;
    margin: 0;
    padding: 0;
}
.shop-cart {
    width: 2rem;
    height: 2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 1rem;
    border: 1px solid rgba(0,0,0,.1);
    text-align: center;
    position: absolute;
    right: 2.5%;
    bottom: 6%;
    z-index: 11;
}
.shop-cart img{
    width: 75%;
    height: 75%;
}
.new-arrival-goodses{
    text-align: left;
    width: 96%;
    margin: 0 auto;
}
.new-arrival-goods{
    width: 47%;
    height: 11rem;
    display: inline-block;
    margin: 0 1.5% 1.5%;
}
.new-arrival-goods-img{
    width: 100%;
    height: 8rem;
}
.new-arrival-goods-info{
    text-align: center;
    display: block;
    width: 100%;
    margin: 0rem;
    position: static;
}
.new-arrival-goods-name{
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.new-arrival-goods-price{
    text-align: left;
    margin-top: .2rem;
}
.new-arrival-goods-income{
    position: absolute;
    bottom: 4%;
    right: 32%;
    width: 2rem;
    height: 1.2rem;
    line-height: 1.2rem;
    font-size: .7rem;
}
.new-arrival-goods-shop-cart{
    width: 1.5rem;
    height: 1.5rem;
    right: 3%;
    bottom: 3%;
}
</style>